package com.zhangsun.expection;

import cn.hutool.log.StaticLog;
import com.zhangsun.base.bean.ResponseData;
import com.zhangsun.common.utils.ResponseUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 统一的异常处理
 */
@ControllerAdvice
public class ShiroExceptionHandler {

    /**
     * token验证异常或未登录的统一处理
     *
     * @param e 异常
     * @return 结果
     */
    @ExceptionHandler(value = AuthenticationException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    public ResponseData userNotFoundHandler(AuthenticationException e) {
        StaticLog.error(e);
        return ResponseUtil.error(String.valueOf(HttpStatus.UNAUTHORIZED.value()), e.getMessage());
    }

    /**
     * 没有权限异常处理
     *
     * @param e 异常
     * @return 结果
     */
    @ExceptionHandler(value = {UnauthorizedException.class, UnauthenticatedException.class})
    @ResponseBody
    @ResponseStatus(value = HttpStatus.FORBIDDEN)
    public ResponseData unauthorizedErrorHandler(AuthorizationException e) {
        StaticLog.error(e);
        return ResponseUtil.error(String.valueOf(HttpStatus.FORBIDDEN.value()), "您没有权限做此操作");
    }

}
